package com.keqiang.chart.impl.radar

import android.graphics.PathEffect
import androidx.annotation.IntDef
import androidx.annotation.IntRange
import kotlin.math.roundToInt

/**
 * 雷达图Y轴
 *
 * @author Created by wanggaowan on 2022/10/27 13:37
 */
open class YAxis : Axis() {
    /**
     * 轴线是否绘制，不设置则默认绘制每一条轴线
     */
    var lineDrawFactory: LineDrawFactory? = { true }

    /**
     * 设置轴线样式，如果设置了此值，则[linePathEffect]无效
     */
    var linePathEffectFactory: LinePathEffectFactory? = null

    /**
     * 是否绘制轴线标签
     */
    var drawLabel: Boolean = false

    /**
     * 标签绘制的起始角度
     */
    var labelDrawStartAngle: Float = -30f

    /**
     * 绘制坐标起始值
     */
    var min: Float = 0f

    /**
     * 绘制坐标结束值
     */
    var max: Float = 100f

    /**
     * 线条的样式，如果是[LineStyle.LINER]则绘制正多边形
     */
    @setparam:LineStyle
    var lineStyle: Int = LineStyle.LINER

    /**
     * 轴上标签数量。比如设置标签数量为6，如果使用默认的ValueFormat,设置Y轴最小、最大值分别为0、100，则Y轴标签值为0，20，40，60，80，100
     */
    @setparam:IntRange(from = 1)
    override var labelCount: Int = 6
        set(value) {
            if (field == value) {
                return
            }

            field = if (value < 1) {
                1
            } else {
                value
            }
        }

    /**
     * 标签格式化，默认雷达图0值绘制不绘制，需要绘制重新设置自定义格式化器即可
     */
    override var axisValueFormat: AxisValueFormat? = object : AxisValueFormat {
        override fun invoke(position: Int): String? {
            if (labelCount <= 0) {
                return null
            }

            if (labelCount == 1 || position == 0) {
                return null
            }

            if (position == labelCount - 1) {
                return max.roundToInt().toString()
            }

            val step = 0f.coerceAtLeast((max - min) / (labelCount - 1))
            return (min + (position * step)).roundToInt().toString()
        }
    }

    override fun apply(axis: Axis) {
        super.apply(axis)
        if (axis is YAxis) {
            this.lineDrawFactory = axis.lineDrawFactory
            this.linePathEffectFactory = axis.linePathEffectFactory
            this.labelDrawStartAngle = axis.labelDrawStartAngle
        }
    }
}

@IntDef(LineStyle.LINER, LineStyle.CIRCLE)
@Target(AnnotationTarget.VALUE_PARAMETER)
@Retention(AnnotationRetention.SOURCE)
annotation class LineStyle {
    companion object {
        /**
         * 直线
         */
        const val LINER = 0

        /**
         * 圆
         */
        const val CIRCLE = 1
    }
}

/**
 * 轴线是否绘制
 */
typealias LineDrawFactory = (position: Int) -> Boolean

/**
 * 轴线是否绘制
 */
typealias LinePathEffectFactory = (position: Int) -> PathEffect?